/***************************************************
 * 此文件的版权归属快程乐码信息科技有限公司所有，未经允许，请勿复制
 */
package com.kclm.se.io.poem;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

/**
 * @author yejf
 * @since JDK8.0
 * @CreateDate 2021年1月20日 下午3:27:11 
 * @description 此类用来描述了 把古诗从横排变成竖排
 *
 */
public class AssignPoem {

	private int length; //长度
	
	private final String _SPACE = " ";
	
	/**
	 * 
	 */
	public AssignPoem() {
		this.length = 6;  // 以5言绝句为准
	}

	
	/**
	 * @param length
	 */
	public AssignPoem(int length) {
		this.length = length;
	}


	/****************
	 * 把古诗从横排变成竖排
	 * @param poemPath 古诗文件的路径
	 */
	public void convertPoem(String poemPath) {
		//1. 判断此文件是否存在
		File poemFile = new File(poemPath);
		//
		if(!poemFile.exists()) {
			System.out.println("古诗文件不存在.");
			return ;
		}
		//
		convertPoem(poemFile);
	}

	private void convertPoem(File poemFile) {
		//1.把古诗读出来形成一串字符串【去掉换行符】
		StringBuilder builder = new StringBuilder();
		File targetPath = new File(poemFile.getParent(),"竖排_"+poemFile.getName());
		try(BufferedReader br = new BufferedReader(new FileReader(poemFile));
				BufferedWriter bw = new BufferedWriter(new FileWriter(targetPath))) {
			String line = null;
			while((line = br.readLine()) != null) {
				//填充不足长度的字符
				line = padding(line.trim());
				//把line添加到 builder中
				builder.append(line);
			}
			//
			System.out.println("中间值："+builder.toString());
			
			//开始转换
			StringBuilder target = assign(builder);
			//
			System.out.println("----------------------------");
			System.out.println(target.toString());
			//写入到文件
			bw.write(target.toString());
			//
			System.out.println("写入完成，路径："+targetPath.getAbsolutePath());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/****
	 * 横排变竖排
	 * @param builder
	 * @return
	 */
	private StringBuilder assign(StringBuilder builder) {
		StringBuilder target = new StringBuilder();
		//
		for(int i = 0; i < this.length; i++) {
			//
			for(int j = 0; j < this.length; j++) {
				target.append(builder.charAt(j * this.length + i));
			}
			//添加换行
			target.append("\n");
		}
		return target;
	}


	/*******
	 * 把不足 length长度的字符串，以空白字符填充
	 * @param line
	 * @return
	 */
	private String padding(String line) {
		//如果当行的字符串长度小于我们指定的length,则进行填充
		if(line.length() < this.length)	 {
			StringBuilder builder = new StringBuilder();
			int prefixLen = (this.length - line.length()) / 2;
			int suffixLen = this.length - prefixLen - line.length();
			//循环
			for(int i = 0;i < prefixLen; i++) {
				builder.append(_SPACE);
			}
			builder.append(line);
			//
			for(int i=0;i<suffixLen;i++) {
				builder.append(_SPACE);
			}
			//
			return builder.toString();
		}
		//
		return line;
	}
}
